/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alipay.sofa.jraft.entity;

import java.io.Serializable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alipay.sofa.jraft.util.Copiable;
import com.alipay.sofa.jraft.util.Endpoint;
import com.alipay.sofa.jraft.util.Utils;

/**
 * Represent a participant in a replicating group.
 *
 * @author boyan (boyan@alibaba-inc.com)
 *
 * 2018-Mar-12 3:27:37 PM
 */
public class PeerId implements Copiable<PeerId>, Serializable {

    private static final long   serialVersionUID = 8083529734784884641L;

    private static final Logger LOG              = LoggerFactory.getLogger(PeerId.class);

    /** peer address */
    private Endpoint            endpoint         = new Endpoint(Utils.IP_ANY, 0);
    /** index in same addr, default is 0. */
    private int                 idx;
    /** cached toString result*/
    private String              str;

    public static final PeerId  ANY_PEER         = new PeerId();

    public PeerId() {
        super();
    }

    /**
     * Create an empty peer.
     * @return empty peer
     */
    public static PeerId emptyPeer() {
        return new PeerId();
    }

    @Override
    public PeerId copy() {
        return new PeerId(this.endpoint.copy(), idx);
    }

    /**
     * Parse a peer from string in the format of "ip:port:idx",
     * returns null if fail to parse.
     *
     * @param s input string with the format of "ip:port:idx"
     * @return parsed peer
     */
    public static PeerId parsePeer(String s) {
        final PeerId peer = new PeerId();
        if (peer.parse(s)) {
            return peer;
        }
        return null;
    }

    public PeerId(Endpoint endpoint, int idx) {
        super();
        this.endpoint = endpoint;
        this.idx = idx;
    }

    public PeerId(String ip, int port) {
        this(ip, port, 0);
    }

    public PeerId(String ip, int port, int idx) {
        super();
        this.endpoint = new Endpoint(ip, port);
        this.idx = idx;
    }

    public Endpoint getEndpoint() {
        return this.endpoint;
    }

    public String getIp() {
        return this.endpoint.getIp();
    }

    public int getPort() {
        return this.endpoint.getPort();
    }

    public int getIdx() {
        return this.idx;
    }

    /**
     * Returns true when ip is ANY_IP, port is zero and idx is zero too.
     */
    public boolean isEmpty() {
        return this.getIp().equals(Utils.IP_ANY) && this.getPort() == 0 && this.idx == 0;
    }

    @Override
    public String toString() {
        if (str == null) {
            str = this.endpoint.toString();
            // ignore idx when it is zero.
            if (this.idx != 0) {
                str += ":" + this.idx;
            }
        }
        return str;
    }

    /**
     * Parse peerId from string that generated by {@link #toString()}
     */
    public boolean parse(String s) {
        final String[] tmps = s.split(":");
        if (tmps.length != 3 && tmps.length != 2) {
            return false;
        }
        try {
            final int port = Integer.valueOf(tmps[1]);
            this.endpoint = new Endpoint(tmps[0], port);
            if (tmps.length == 3) {
                this.idx = Integer.valueOf(tmps[2]);
            } else {
                this.idx = 0;
            }
            this.str = null;
            return true;
        } catch (final Exception e) {
            LOG.error("Parse peer from string failed: {}", s, e);
            return false;
        }
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + (this.endpoint == null ? 0 : this.endpoint.hashCode());
        result = prime * result + this.idx;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final PeerId other = (PeerId) obj;
        if (this.endpoint == null) {
            if (other.endpoint != null) {
                return false;
            }
        } else if (!this.endpoint.equals(other.endpoint)) {
            return false;
        }
        return this.idx == other.idx;
    }
}
